package com.techzhi.tidb.autoconfigure;


import com.techzhi.tidb.config.TiDBConfigManager;
import com.techzhi.tidb.loader.TiDBUtilsLoader;
import com.techzhi.tidb.pool.TiDBConnectionPoolManager;
import com.techzhi.tidb.service.TiDBService;
import com.techzhi.tidb.utils.TiDBOperationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * TiDB自动配置类
 * 实现Spring Boot SPI机制，自动装配TiDB相关Bean
 *
 * @author shouzhi
 * @date 2025-09-01
 */

@Slf4j
@Configuration
@ConditionalOnClass({
    com.mysql.cj.jdbc.Driver.class,
    com.zaxxer.hikari.HikariDataSource.class
})
@ConditionalOnProperty(name = "tidb.enabled", havingValue = "true")
@EnableConfigurationProperties(TiDBConfigManager.class)
public class TiDBAutoConfiguration {

    public TiDBAutoConfiguration() {
        log.info("TiDB自动配置开始加载...");
    }


    /**
     * 连接池管理器Bean
     * 负责管理TiDB连接池的生命周期
     * Spring会自动处理@Autowired依赖注入
     */
    @Bean
    @ConditionalOnMissingBean
    public TiDBConnectionPoolManager tiDBConnectionPoolManager() {
        log.debug("创建TiDBConnectionPoolManager Bean");
        return new TiDBConnectionPoolManager();
    }

    /**
     * 操作工具类Bean
     * 提供TiDB的CRUD操作封装
     * Spring会自动处理@Autowired依赖注入
     */
    @Bean
    @ConditionalOnMissingBean
    public TiDBOperationUtils tiDBOperationUtils() {
        log.debug("创建TiDBOperationUtils Bean");
        return new TiDBOperationUtils();
    }

    /**
     * 动态加载器Bean
     * 负责TiDB组件的动态加载和生命周期管理
     * Spring会自动处理@Autowired依赖注入
     */
    @Bean
    @ConditionalOnMissingBean
    public TiDBUtilsLoader tiDBUtilsLoader() {
        log.debug("创建TiDBUtilsLoader Bean");
        return new TiDBUtilsLoader();
    }

    /**
     * TiDB服务Bean
     * 提供统一的TiDB操作入口
     * Spring会自动处理@Autowired依赖注入
     */
    @Bean
    @ConditionalOnMissingBean
    public TiDBService tiDBService() {
        log.debug("创建TiDBService Bean");
        TiDBService tidbService = new TiDBService();
        log.info("TiDB自动配置完成，所有Bean已注册");
        return tidbService;
    }
}
